package cn.com.agree.mybatisporelation.one2many.service.impl;

import cn.com.agree.mybatisporelation.one2many.controller.dto.AuthorDTO;
import cn.com.agree.mybatisporelation.one2many.dao.mapper.AuthorMapper;
import cn.com.agree.mybatisporelation.one2many.dao.po.AuthorPO;
import cn.com.agree.mybatisporelation.one2many.service.AuthorService;
import cn.com.agree.mybatisporelation.one2many.service.exception.BizAuthorException;
import cn.hutool.core.bean.copier.BeanCopier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AuthorServiceImpl implements AuthorService {

    @Autowired
    private AuthorMapper authorMapper;

    @Override
    public AuthorDTO addAuthor(AuthorDTO authorDTO) {
        AuthorPO authorPO = BeanCopier.create(authorDTO, new AuthorPO(), null).copy();
        authorMapper.insert(authorPO);
        return BeanCopier.create(authorPO, new AuthorDTO(), null).copy();
    }

    @Override
    public AuthorDTO getAuthor(Long id) {
        AuthorPO authorPO = authorMapper.findById(id);
        if (Objects.isNull(authorPO)) {
            throw new BizAuthorException("作者不存在。");
        }
        return BeanCopier.create(authorPO, new AuthorDTO(), null).copy();
    }

    @Override
    public AuthorDTO getAuthorAnotherWay(Long id) {
        AuthorPO authorPO = authorMapper.findByIdAnotherWay(id);
        if (Objects.isNull(authorPO)) {
            throw new BizAuthorException("作者不存在。");
        }
        return BeanCopier.create(authorPO, new AuthorDTO(), null).copy();
    }

}
